//
//  HomePageViewController.m
//  BaishidaiKnight
//
//  Created by mac book on 2019/1/24.
//  Copyright © 2019年 sy. All rights reserved.
//

#import "HomePageViewController.h"
#import "TaskDetailViewController.h"
#import "FinishTaskViewController.h"
#import "MySettingViewController.h"
#import "MyBalanceViewController.h"

#import "SelectSegmentView.h"

#import "NewTaskHeaderView.h"
#import "NewTaskFooterView.h"
#import "NewTaskTableViewCell.h"


#import "WaitTakeFooterView.h"


#import "ShippedTableViewCell.h"


#define SEGHEIGHT 40/HEIGHT_6S_SCALE
#define Cell_H  60.f/HEIGHT_6S_SCALE


@interface HomePageViewController ()<UITableViewDelegate,UITableViewDataSource,NewTaskFooterDelegate,ShippedTaskDelegate,DZNEmptyDataSetDelegate,DZNEmptyDataSetSource>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong) BSDPager* page;

@property (nonatomic,assign) NSInteger  selectedIndex;

@property (nonatomic,strong)SelectSegmentView *segView;
@property (nonatomic, strong) NSArray *pagesArray;

@property (nonatomic, strong) NSMutableArray *listDataArray; // 外卖数据源

@property (nonatomic, strong) TaskModel *taskModel;

@property(nonatomic,strong) NSString* cellIdentifier;


@end

@implementation HomePageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.title = @"任务列表";
    self.cellIdentifier = @"NewTaskCell";
  
    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"icon_left_menu"] style:UIBarButtonItemStylePlain target:self action:@selector(presentLeftMenuViewController:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"icon_right_kefu"] style:UIBarButtonItemStylePlain target:self action:@selector(kefuButtonDidClick)];

    
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    self.pagesArray = [NSArray arrayWithObjects:@"新任务",@"待取货",@"配送中", nil];

    [self creatSubViews];

    // 启动倒计时管理
    [kCountDownManager start];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finsishedTaskNotification:) name:NotificationToFinishedTask object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(settingNotification:) name:NotificationToSetting object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(accountNotification:) name:NotificationToAccount object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(MineTongJiNotification:) name:NotificationMineTongJi object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshMainData:) name:NotificationRefreshMainData object:nil];

}


-(void)creatSubViews{
    
    self.selectedIndex = 1;
    
    _segView = [[SelectSegmentView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SEGHEIGHT) titles:self.pagesArray clickBlick:^void(NSInteger index) {
        self.selectedIndex = index;
        
        self.page.pageIndex = 1;
        [self.tableView.mj_header beginRefreshing];

    }];
    _segView.defaultIndex = 1;
    _segView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    _segView.titleSelectColor =  [UIColor colorWithRed:248/255.f green:159/255.f blue:39/255.f alpha:1.0];
    _segView.lineUnSelectColor = [UIColor whiteColor];
    _segView.titleFont =kFontNameSize(15);
    [self.view addSubview:_segView];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_segView.frame), CGRectGetWidth(self.view.frame),  CGRectGetHeight(self.view.frame) - CGRectGetMaxY(_segView.frame) - NAVGATIONBAR_HEIGHT) style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    
    
    if (@available(iOS 11.0, *))
    {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
    }
    
    
    [self.tableView registerClass:[NewTaskTableViewCell class] forCellReuseIdentifier:@"NewTaskTableViewCell"];
    [self.tableView registerClass:[ShippedTableViewCell class] forCellReuseIdentifier:@"ShippedTableViewCell"];

    
    [self refereshDatasource];

    
    
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    self.page.pageIndex = 1;

    [self.tableView.mj_header beginRefreshing];

}

#pragma mark - Data source
-(void)getData{
    
    UserInfoModel *model = [UserHandle shareInstance].userInfo;
    if([UserHandle shareInstance].locationInfo.enabled){

    }
    
    NSDictionary* arg;
    
    if (self.selectedIndex == 1) {
        
        arg = @{@"ince":@"get_rr_help_order_list",
                @"lat":model.lat,
                @"lng":model.lng
                
                };
    }else if (self.selectedIndex == 2){
        
      arg = @{
              @"ince":@"get_rr_help_wait_order_list",
              @"emp_id":[UserHandle shareInstance].userId
              
              };
        
    }else{
        
        arg = @{
                @"ince":@"get_rr_help_send_order_list",
                @"emp_id":[UserHandle shareInstance].userId
                };

    }
    
    
    [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
        NSLog(@"主页 = %@",data);
        
        if(self.page.pageIndex == 1){
            [self.page.arrayData removeAllObjects];
        }
        NSInteger flag = [[data objectForKey:@"status"]integerValue];
        if(flag == 1){
    

            [self.listDataArray removeAllObjects];
            
            self.taskModel = [TaskModel mj_objectWithKeyValues:data];
            [self.listDataArray addObjectsFromArray:self.taskModel.list];
            
        }else{
            [self alertHUD:[data objectForKey:@"fail"]];
        }
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        
    } failure:^(NSError *error) {
        [self alertHUD:@"网络异常"];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
    
}

-(void)refereshDatasource{
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf getData];
    }];
}

#pragma mark - tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.listDataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return Cell_H;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.selectedIndex == 3) {

        
        ShippedTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShippedTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        TaskModel *model =  self.listDataArray[indexPath.section];
        cell.taskModel = model;
        
        return cell;
        
    }else{
        
        NewTaskTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewTaskTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        
        TaskModel *model =  self.listDataArray[indexPath.section];
        if (self.selectedIndex == 1) {
            [cell setTaskModel:model withType:1];
            
        }else{
            [cell setTaskModel:model withType:2];
            
        }
        
        
        
        return cell;
        
        
    }
    
    
    
   
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (self.selectedIndex != 1) {

        TaskModel *model =  self.listDataArray[indexPath.section];

        TaskDetailViewController *controller = [[TaskDetailViewController alloc]init];
        controller.taskModel = model;
        if (self.selectedIndex == 2) {
            controller.isSend = NO;

        }else{
            controller.isSend = YES;

        }
        [self.navigationController pushViewController:controller animated:YES];
        
        
    }
    
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    if (self.selectedIndex == 1) {

        return 170;
    }else{
        
        return 160;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    
    return 75;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    NewTaskHeaderView *headerView = [[NewTaskHeaderView alloc] init];
    
    if (self.listDataArray.count > 0) {
            headerView.taskModel = self.listDataArray[section];

    }
    
    return headerView;
    
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{

    if (self.selectedIndex == 1) {

        NewTaskFooterView *footerView = [[NewTaskFooterView alloc] init];
        footerView.delegate = self;
        footerView.taskModel = self.listDataArray[section];
        
        return footerView;
        
        
    }else{
        
        [kCountDownManager addSourceWithIdentifier:[NSString stringWithFormat:@"OYPagingSource%zd", section]];

        WaitTakeFooterView *footerView = [[WaitTakeFooterView alloc] init];
        footerView.taskModel = self.listDataArray[section];
        footerView.countDownListZero = ^(TaskModel *taskModel) {
            // 回调
            if (!taskModel.timeOut) {
                [self.tableView reloadData];
                NSLog(@"--时间到了");
            }
            // 标志
            taskModel.timeOut = YES;
        };
        
        return footerView;

    }
  
    
}


//抢单
- (void)NewTaskFooterView:(TaskModel*)taskModel{
    
    
    TaskModel *itemModel = taskModel.items.firstObject;

    [self showHUD];
    NSDictionary* arg = @{
                          @"ince":@"qs_qiang_new",
                          @"emp_id":[UserHandle shareInstance].userId,
                          @"main_id":itemModel.order_id
                          
                          };

    [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
        NSLog(@"data = %@",data);
        NSInteger flag = [[data objectForKey:@"status"]integerValue];
        if(flag == 1){
            
            [self hidHUD:@"成功" success:YES];
            [self.tableView.mj_header beginRefreshing];
            
        }else{
            [self hidHUD:[data objectForKey:@"msg"]];
        }
        
    } failure:^(NSError *error) {
        [self hidHUD:@"网络异常"];
    }];
    
}


//确认送达
-(void)ConfirmTask:(TaskModel *)taskModel{
    
    [self showHUD];
    
    TaskModel *itemModel = taskModel.items.firstObject;

    NSDictionary* arg = @{@"ince":@"qs_send_food",
                          @"emp_id":[UserHandle shareInstance].userId,
                          @"order_id":itemModel.order_id
                          
                          };
    
    [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
        NSLog(@"data = %@",data);
        NSInteger flag = [[data objectForKey:@"status"]integerValue];
        if(flag == 1){
            NSString *sucess = data[@"sucess"];
            [self hidHUD:sucess success:YES];

            [self.tableView.mj_header beginRefreshing];

        }else{
            [self hidHUD:[data objectForKey:@"fail"]];
        }
        
    } failure:^(NSError *error) {
        [self hidHUD:@"网络异常"];
    }];
    
}

#pragma mark - property package
-(BSDPager *)page{
    if(!_page){
        _page = [[BSDPager alloc]init];
        _page.pageIndex = 1;
        
    }
    return _page;
}
- (NSMutableArray *)listDataArray
{
    if (!_listDataArray) {
        _listDataArray = @[].mutableCopy;
    }
    return _listDataArray;
}

#pragma mark - Notificaton
// 已完成的跑腿任务
-(void)RunBuyOverNotification:(NSNotification*)notification{
//    RunBuyOverViewController* controller = [[RunBuyOverViewController alloc]init];
//    [self.navigationController pushViewController:controller animated:YES];
}
// 我的统计
-(void)MineTongJiNotification:(NSNotification*)notification{
//    MineTongJiViewController* controller = [[MineTongJiViewController alloc]init];
//    [self.navigationController pushViewController:controller animated:YES];
}
// 已完成的任务
-(void)finsishedTaskNotification:(NSNotification*)notification{

    FinishTaskViewController * VC = [[FinishTaskViewController alloc]init];
    [self.navigationController pushViewController:VC animated:YES];
}

-(void)settingNotification:(NSNotification*)notification{
    MySettingViewController* VC = [[MySettingViewController alloc]init];
    [self.navigationController pushViewController:VC animated:YES];
}

-(void)accountNotification:(NSNotification*)notification{
    MyBalanceViewController* VC = [[MyBalanceViewController alloc]init];
    [self.navigationController pushViewController:VC animated:YES];
}



-(void)kefuButtonDidClick{
    
    UserInfoModel *model = [UserHandle shareInstance].userInfo;
    NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",model.kf_tel];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
    
}


-(void)refreshMainData:(NSNotification*)notification{
    
    self.selectedIndex = 1;
    self.page.pageIndex = 1;
    [self.tableView.mj_header beginRefreshing];

}


#pragma mark - DZNEmptyDataSetDelegate

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    return [[NSAttributedString alloc] initWithString:@"附近暂时没有任务" attributes:@{NSFontAttributeName :[UIFont boldSystemFontOfSize:17.0],NSForegroundColorAttributeName:kMyColor(131, 131, 131)}];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    return [UIImage imageNamed:@"placeholder_order_null"];
}

- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
{
    NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
    // paragraph.lineBreakMode = NSLineBreakByWordWrapping;
    paragraph.alignment = NSTextAlignmentCenter;
    return  [[NSMutableAttributedString alloc] initWithString:@"休息一会\"刷新列表\"试试" attributes:@{NSForegroundColorAttributeName:kMyColor(191, 191, 191),NSParagraphStyleAttributeName:paragraph,NSFontAttributeName:[UIFont boldSystemFontOfSize:15.f]}];
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
//{
//    return 20;
//}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
